<template>
  <el-dialog :model-value="setPwdDialogVisible" title="修改密码" width="50%" :show-close="false" top="5%"
    @close="closeDialog">
    <template #header>
      <div class="py-[13px] px-[16px] flex items-center justify-between border-b border-solid border-[#E8E8E8]">
        <span class="text-[18px] font-bold">重置密码</span>
        <el-icon @click="closeDialog" class="cursor-pointer">
          <Close />
        </el-icon>
      </div>
    </template>

    <div class="px-[40px] pb-[32px]">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="mt-[20px]">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="formData.oldPassword" type="password" placeholder="请输入原密码" show-password
            style="width: 100%;" />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="formData.newPassword" type="password" placeholder="请输入新密码（不少于6位）" show-password
            style="width: 100%;" />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="formData.confirmPassword" type="password" placeholder="请再次输入新密码" show-password
            style="width: 100%;" />
        </el-form-item>
      </el-form>

      <div class="flex justify-end mt-[32px]">
        <Button type="cancel" class="mr-[16px]" @click="closeDialog">取消</Button>
        <Button type="primary" @click="handleSubmit" :loading="loading">确定</Button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from "vue";
import { Close } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { userApi } from "../../api/user";
import { useToken } from '@/store/useToken';
import { useUser } from '@/store/useUser';
import { useRouter } from 'vue-router';
const router = useRouter();
const token = useToken();
const user = useUser();

const emit = defineEmits(['update:setPwdDialogVisible']);

const { setPwdDialogVisible } = defineProps({
  setPwdDialogVisible: {
    type: Boolean,
    default: false
  }
});

const formRef = ref();
const loading = ref(false);

const formData = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 自定义验证规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'));
  } else if (value !== formData.newPassword) {
    callback(new Error('两次输入密码不一致'));
  } else {
    callback();
  }
};

const rules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ]
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    const valid = await formRef.value.validate();
    if (!valid) return;

    loading.value = true;

    // 调用重置密码接口
    const [err, res] = await userApi.updatePwd({
      oldPwd: formData.oldPassword,
      newPwd: formData.newPassword
    });
    if (err) {
      ElMessage.error('修改密码失败');
      return;
    }

    ElMessage.success('密码修改成功');
    closeDialog();
    //
    token.clear();
    user.clear();
    router.push({
      path: "/",
    });

  } catch (error) {
    console.error('重置密码失败:', error);
    ElMessage.error('修改密码失败');
  } finally {
    loading.value = false;
  }
};

// 关闭对话框
const closeDialog = () => {
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields();
  }

  // 重置数据
  Object.assign(formData, {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  });

  emit('update:setPwdDialogVisible', false);
};
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  padding: 0 !important;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
}
</style>


